package cn.edu.gznu.wecampus.core.common.entity.jpa;

import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import cn.edu.gznu.wecampus.core.ApplicationContextHolder;
import cn.edu.gznu.wecampus.core.JpaEntity;
import cn.edu.gznu.wecampus.core.common.repository.jpa.UserRoleRepository;
import lombok.Getter;
import lombok.Setter;

@Entity
@Table(name = "tb_common_user",
	indexes = {
		@Index(name = "idx_tb_common_user_username", columnList = "username")
	},
	uniqueConstraints = {
		@UniqueConstraint(name = "uni_tb_common_user_username", columnNames = "username")
	}
)
@Getter
@Setter
public class User extends JpaEntity<String> {
	
	@Column(name = "username", nullable = false)
	private String username;

	@Column(name = "password_hex", nullable = false)
	@JsonIgnore
	private String passwordHex;
	
	@Column(name = "realname", nullable = false)
	private String realname;
	
	@JsonProperty("roleIds")
	public List<String> roleIds() {
		UserRoleRepository userRoleRepository = ApplicationContextHolder.getBean(UserRoleRepository.class);
		return userRoleRepository.findByUser(this).stream()
			.map(userRole -> userRole.getRoleId())
			.collect(Collectors.toList());
	}
}
